﻿using MaterialDesignColors;
using MaterialDesignColors.ColorManipulation;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Windows;
using System.Windows.Media;
using WpfMvvmTemplate.MD.Common;

namespace WpfMvvmTemplate.MD.Views.Windows
{
    /// <summary>
    /// SkinWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SkinWindowView : Window
    {
        private string btnBrush = string.Empty;
        private bool temp = false;

        public SkinWindowView()
        {
            InitializeComponent();
            btnBrush = JsonConvert.SerializeObject(cancelBtn.Background);
        }

        /// <summary>
        /// 确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_Determine(object sender, RoutedEventArgs e)
        {
            SaveBrush();
            Close();
        }

        /// <summary>
        /// 取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cancelBtn_Click_Cancel(object sender, RoutedEventArgs e)
        {
            temp = true;

            var paletteHelper = new PaletteHelper();
            ITheme theme = paletteHelper.GetTheme();

            // 恢复到初始默认的颜色
            Color hue = JsonConvert.DeserializeObject<Color>(btnBrush)!;
            theme.PrimaryLight = new ColorPair(hue.Lighten());
            theme.PrimaryMid = new ColorPair(hue);
            theme.PrimaryDark = new ColorPair(hue.Darken());
            paletteHelper.SetTheme(theme);
            Close();
        }

        /// <summary>
        /// 重写窗体关闭事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if(!temp) { SaveBrush(); }
        }

        /// <summary>
        /// 保存颜色到配置文件中
        /// </summary>
        private void SaveBrush()
        {
            //读取文件内容
            string fileContent = File.ReadAllText(GlobalStaticData.AppSettingsFilePath);
            JObject? jObject = JObject.Parse(fileContent);

            //解析文件内容
            string json = JsonConvert.SerializeObject(ColorPicker.Color);
            JToken newJToken = JToken.Parse(json);
            jObject?["AppSettings"]?["SelectedBrush"]?.Replace(newJToken);

            //保存中英文到配置文件中
            File.WriteAllText(GlobalStaticData.AppSettingsFilePath, jObject?.ToString());
        }

    }
}